package com.sergio.compress.cp.mainUtil;

import com.sergio.compress.cp.base.CompressResult;
import com.sergio.compress.cp.base.CompressTest;
import com.sergio.compress.cp.base.DecompressResult;
import com.sergio.compress.cp.base.TestSource;
import org.springframework.util.StopWatch;

import java.io.IOException;
import java.util.Date;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.GZIPOutputStream;
import java.util.zip.Inflater;

import static com.sergio.compress.cp.base.Const.BUFFER_SIZE;

/**
 * @Author : Sergio.D
 * @Description :
 * @CreateDate ：2023/6/14 18:15
 */
public class ZLIB extends CompressTest {
    @Override
    public String getType() {
        return "ZLIB";
    }

    @Override
    public CompressResult compress(TestSource testSource) throws IOException {
        StopWatch stopWatch = new StopWatch();
            stopWatch.start();
        Deflater deflater = new Deflater();
        deflater.setInput(testSource.getSourceData());
        deflater.finish();
        byte[] compressed = new byte[BUFFER_SIZE];
//        byte[] compressed = new byte[testSource.getSourceLength()];
        int compressedLength = deflater.deflate(compressed);
        deflater.end();
        stopWatch.stop();
        return new CompressResult(getType(), stopWatch.getTotalTimeNanos(), compressed, testSource.getSourceLength(), compressedLength);
    }

    @Override
    public DecompressResult decompress(CompressResult testSource) throws IOException, DataFormatException {
        StopWatch stopWatch = new StopWatch();
            stopWatch.start();
        Inflater inflater = new Inflater();
        inflater.setInput(testSource.getData(), 0, testSource.getData().length);

        byte[] decompressed = new byte[BUFFER_SIZE];
//        byte[] decompressed = new byte[testSource.getLengthSource()];
        int decompressedLength = inflater.inflate(decompressed);
        inflater.end();
        stopWatch.stop();
        return new DecompressResult(getType(), stopWatch.getTotalTimeNanos(), decompressed, testSource.getLengthSource(), decompressedLength);
    }
}
